use std::option::Option::Some;

#[derive(PartialEq, Eq, Clone, Debug)]
pub struct ListNode {
    pub val: i32,
    pub next: Option<Box<ListNode>>,
}

impl ListNode {
    #[inline]
    pub fn new(val: i32) -> Self {
        ListNode {
            next: None,
            val,
        }
    }

    pub fn len(&self) -> i32 {
        let mut len = 1;
        let mut next = self.next.clone();
        while let Some(n) = next {
            len += 1;
            next = n.next;
        }
        len
    }
}

impl From<Vec<i32>> for Box<ListNode> {
    fn from(vec: Vec<i32>) -> Self {
        assert!(!vec.is_empty());

        let len = vec.len();

        if len == 1 {
            return Box::new(ListNode::new(vec[0]));
        }

        let mut tail = Box::new(ListNode::new(vec[len - 1]));
        for val in vec.into_iter().take(len - 1).rev() {
            let mut tmp = Box::new(ListNode::new(val));
            tmp.next = Some(tail);
            tail = tmp;
        }

        tail
    }
}

impl Into<Vec<i32>> for Box<ListNode> {
    fn into(self) -> Vec<i32> {
        let mut head = Some(self);
        let mut res = vec![];
        while let Some(val) = head {
            res.push(val.val);
            head = val.next;
        }
        res
    }
}
